package com.zhb.core.utils;

import org.apache.commons.beanutils.converters.AbstractConverter;

/**
 * 字符串转换器，用来辅助Apache Common BeanUtils实现对象属性到字符串的转换。
 * <p>
 * apache common beanutils的<code>StringConverter</code>不支持日期类型的格式化字符串转换。
 * 部分代码从<code>StringConverter</code>拷贝。
 * 
 * @author dht
 */
@SuppressWarnings("all")
public class HxStringConverter extends AbstractConverter {
    /**
     * Construct a <b>java.lang.String</b> <i>Converter</i> that throws
     * a <code>ConversionException</code> if an error occurs.
     */
    public HxStringConverter() {
        super();
    }

    /**
     * Construct a <b>java.lang.String</b> <i>Converter</i> that returns
     * a default value if an error occurs.
     *
     * @param defaultValue The default value to be returned
     * if the value to be converted is missing or an error
     * occurs converting the value.
     */
    public HxStringConverter(Object defaultValue) {
        super(defaultValue);
    }

    /**
     * Return the default type this <code>Converter</code> handles.
     *
     * @return The default type this <code>Converter</code> handles.
     * @since 1.8.0
     */
	protected Class getDefaultType() {
        return String.class;
    }

    /**
     * Convert the specified input object into an output object of the
     * specified type.
     *
     * @param type Data type to which this value should be converted.
     * @param value The input value to be converted.
     * @return The converted value.
     * @throws Throwable if an error occurs converting to the specified type
     * @since 1.8.0
     */
	protected Object convertToType(Class type, Object value) throws Throwable {
        if(java.util.Date.class==type){
            return DateUtil.formatDate((java.util.Date)value);
        }else if(java.sql.Timestamp.class==type){
            return DateUtil.formatDateTime((java.util.Date)value);
        }else{
            return value.toString();
        }
    }
    
    protected String convertToString(Object value) throws Throwable {
        if(value instanceof java.util.Date){
            return DateUtil.formatDate((java.util.Date)value);
        }else if(value instanceof java.sql.Timestamp){
            return DateUtil.formatDateTime((java.util.Date)value);
        }else{
            return value.toString();
        }
    }
}
